package com.ccjk.beusoft.thirdlib.mockRetrofit;

import com.ccjk.beusoft.thirdlib.mockRetrofit.method.ServiceMethod;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by CCJK on 2017/12/20.
 */

public class MyRetrofit {
    private static class Singleton {
        private static MyRetrofit instance = new MyRetrofit();
    }

    private MyRetrofit() {
    }

    private ConcurrentHashMap<Method, ServiceMethod> methodService = new ConcurrentHashMap<>();

    public static MyRetrofit getInstance() {
        return Singleton.instance;
    }


    public <T> T create(Class<T> service) {

        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[]{service}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                return getServiceMethod(method, args).invoke();
            }
        });
    }

    private ServiceMethod getServiceMethod(Method method, Object[] args) {
        ServiceMethod serviceMethod = methodService.get(method);
        if (serviceMethod != null) {
            return serviceMethod;
        }
        serviceMethod = new ServiceMethod(method, args);
        return serviceMethod;
    }

}
